package com.fang.algorithm.leecode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 二叉树的中序遍历（递归）
 * 给定一个二叉树的根节点 root ，返回 它的 中序 遍历
 * <p>
 * 输入：root = [1,null,2,3]
 * 输出：[1,3,2]
 * <p>
 * 输入：root = []
 * 输出：[]
 * <p>
 * 输入：root = [1]
 * 输出：[1]
 * <p>
 * 注：中序遍历：左子树——根节点——右子树
 * @date 2022/5/15 2:22 下午
 **/
public class L94_InorderTraversal {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1, null, new TreeNode(2, new TreeNode(3), null));
        List<Integer> ans = inorderTraversal(root);
        System.out.println(ans);
    }

    private static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        inorder(root, ans);
        return ans;
    }

    private static void inorder(TreeNode root, List<Integer> ans) {
        if (root == null) {
            return;
        }
        inorder(root.left, ans);
        ans.add(root.val);
        inorder(root.right, ans);
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
